package com.haredot.handler;

import com.haredot.vo.R;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@RestControllerAdvice
public class ValidationHandler {

    @ExceptionHandler(BindException.class)
    public R<?> validationException(BindException exception) {
        // 获取参数校验失败的原因
        BindingResult bindingResult = exception.getBindingResult();

        HashMap<String, String> errors = bindingResult.getFieldErrors().stream().reduce(new HashMap<>(), (map, fieldError) -> {
            String key = fieldError.getField();
            String val = fieldError.getDefaultMessage();
            map.put(key, val);
            return map;
        }, (a, b) -> a);
        return R.fail().data(errors);
    }
}
